package http;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Http请求处理, get/post method
 */
public final class HttpUtil {
  public static final int MIN_TIME_OUT = 50;
  public static final int MAX_TIME_OUT = 1500;

  /**
   * 日志
   */
  protected static final Logger LOG = LoggerFactory.getLogger(HttpUtil.class);

  private HttpUtil() {
  }





  /**
   * 处理get请求
   *
   * @throws Exception
   */
  public static String sendGet(String url) throws Exception {
    return sendGet(url, MAX_TIME_OUT);
  }

  /**
   * 处理get请求
   *
   * @throws IOException
   * @throws MalformedURLException
   */
  public static String sendGet(String url, int maxTimeOut) throws MalformedURLException, IOException {
    StringBuffer sb = new StringBuffer("");
    BufferedReader br = null;

    try {
      URLConnection conn = new URL(url).openConnection();
      conn.setConnectTimeout(maxTimeOut);
      conn.setReadTimeout(maxTimeOut);
      System.out.println(conn);
      Object content = conn.getContent();
      br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String s = null;
      while ((s = br.readLine()) != null) {
        sb.append(s);
      }
      br.close();
    } finally {
      if (br != null) {
        br.close();
      }
    }
    return sb.toString();
  }


  /**
   * 处理get请求
   *
   * @throws IOException
   * @throws MalformedURLException
   */
  public static String sendGet(String url,  Map<String, String> header) throws MalformedURLException, IOException {
    StringBuffer sb = new StringBuffer("");

    try {
      CloseableHttpClient httpclient = HttpClients.createDefault();
      HttpGet httpGet = new HttpGet(url);
//      HttpGet httpGet = new HttpGet(urlEncode(url));
      for (Map.Entry<String, String> entry : header.entrySet()) {
        httpGet.setHeader(entry.getKey(), entry.getValue());
      }
      CloseableHttpResponse response = httpclient.execute(httpGet);
      //8，获取请求返回码
      int statusCode = response.getStatusLine().getStatusCode();
      //9如果请求返回码是200，则说明请求成功
      if (statusCode == 200) {
        //10,获取返回实体
        HttpEntity entity = response.getEntity();
        //11,通过EntityUtils的一个工具类获取返回的内容
        String str = EntityUtils.toString(entity);
//        System.out.println("请求成功的返回内容：" + str);
        sb.append(str);
      } else {
        LOG.error("url {} visit fail",url);
//        System.out.println("请求失败！");
        return null;
      }
    } finally {

    }
    return sb.toString();
  }

  /**
   * URLEncoder编码
   *
   * @param text 待编码文本
   * @return 编码后结果
   */
  public static String urlEncode(String text) {
    try {
      if (StringUtils.isEmpty(text)) {
        return "";
      }
      return StringUtils.replace(URLEncoder.encode(text, "UTF-8"), "+", "%20");
    } catch (UnsupportedEncodingException e) {
      return text;
    }
  }


  public static void main(String[] args) {

//    try {
//      String s = sendGdet("https://m.ctrip.com/webapp/hotel/oversea/73", 5000);
//    } catch (IOException e) {
//      e.printStackTrace();
//    }

    try {
      String s = sendGet("http://elasticsearch-kibana.fnwintranet.com/api/saved_objects/_find?type=index-pattern&search_fields=title&search=my*", 5000);
      System.out.println(s);
    } catch (IOException e) {
      e.printStackTrace();
    }

  }

}
